from functools import wraps

from django.http import JsonResponse
from django.shortcuts import render
# from App_ReadNovel.models import UserisNice, collection
from App_ReadNovel.models import wordlist
from App_SearchNovel.Tools import ParseBook
# Create your views here.
from App_SearchNovel.models import Books
from App_User_SigninAndRegister.models import User
from App_SearchNovel.Tools import *
from NiceNovel.tool import *


def home(request):
    return render(request, 'booklist.html', homedata(request, Books.objects.all()))


def inputSearch(request):
    keyword = request.GET.get("keyword")
    return render(request, "booklist.html", homedata(request, Books.objects.filter(title__icontains=keyword)))


def getCategory(request, category):
    return render(request, "booklist.html", homedata(request, Books.objects.filter(category=category)))


def getBook(request, bookid):
    status = request.session.get("islogin", False)
    iscol = "已收藏"
    nice = "已点赞"
    userid = request.session.get("userid")
    if status:
        try:
            User.objects.get(userid=userid).user_iscollection.get(bookid=bookid)
        except:
            iscol = "收藏"
        try:
            User.objects.get(userid=userid).user_isnice.get(bookid=bookid)
        except:
            nice = "点赞"
    return render(request, bookid + ".html", {"isnice": nice, "iscol": iscol, "bookid": bookid, "userid": userid})


@forlogin(url="signin.html")
def recordList(request):
    try:
        userid = request.session.get("userid")
        u = User.objects.get(userid=userid)
        return render(request, "booklist.html", homedata(request, u.record.all()))
    except:
        return render(request, "booklist.html", homedata(request))


@forlogin(url="signin.html")
def wordList(request):
    userid = request.session.get("userid")
    return render(request, "wordlist.html",
                  {"userid": userid, "data": parseWord(User.objects.get(userid=userid).wordlist.all())})


def delword(request):
    userid = request.session.get("userid")
    User.objects.get(userid=userid).wordlist.remove(wordlist.objects.get(id=request.GET.get("wordid")))
    return JsonResponse({})


def hot(request):
    return render(request, "booklist.html", homedata(request, Books.objects.order_by("-nice")[:6]))


@forlogin(url="signin.html")
def collecteBooks(request):
    try:
        userid = request.session.get("userid")
        u = User.objects.get(userid=userid)
        return render(request, "booklist.html", homedata(request, u.user_iscollection.all()))
    except:
        return render(request, "booklist.html", homedata(request, u.user_iscollection.all()))
